<script setup lang="ts">
import LogisticsApi from "@/api/logistics/index";
import { LogisticsStore } from "@/store/modules/logistics";
import { EquipmentInfo } from "@/api/logistics/model";
import { ref, reactive, onMounted,computed } from "vue";
import { FormRules } from "element-plus";
import { exportExcel } from "@/utils/exportTable";

const logisticsStore:any=LogisticsStore();
let showEditWindow=ref(false);
let isAddMode=ref(false)
let equipmentStore:EquipmentInfo[]=logisticsStore.equipment;
// 根据多少条数据分页
let limit=ref(10);
// 当前页
let page=ref(1);
// 搜索设备名称
let searchE=ref('')
// 获取表的数据
const getEquipments=()=>{
  return LogisticsStore().getEquipmentInfo()
};
const emptyData:EquipmentInfo={
  id:0,
  name:'',
  location:'',
  status:"available",
  createdAt: new Date()
}
// 提供可选值给下拉列表
const statusList=[ "available" , "borrowed" , "maintenance" , "discarded"]

let newData=ref(emptyData)
let oldData=ref(emptyData)

const dataRules = computed(():EquipmentInfo => {
  return {
    name: [
      {
        required: true,
        trigger: "blur"
      },
    ],
    location: [
      {
        required: true,
        trigger: "blur"
      }
    ],
    status: [
      {
        required: true,
        trigger: "blur"
      },
    ],
    createAt: [
      {
        required: false,
        trigger: "blur"
      }
    ]
  };
});
const showFormWindow=(addMode:boolean)=>{
  isAddMode.value=addMode;
  showEditWindow.value=true;
}
const confirmData=()=>{
  newData.value.createdAt=formatDate(newData.value.createdAt)
  if (isAddMode.value) {
    newData.value.id = 0;
    LogisticsApi.insertEquipment(newData.value).then(r => {
      getEquipments().then(r => {
        ElMessage.success("添加成功");
        showEditWindow.value = false;
      });
    });
  }
  else
    LogisticsApi.updateEquipment(newData.value).then(r=>{
      getEquipments().then(r=>{
        ElMessage.success("更新成功")
        showEditWindow.value=false
      })
    })
}
const resetData=()=>{
  newData.value=toIndependent(oldData.value)
}
const clearData=()=>{
  newData.value=toIndependent(emptyData)
}
const handleEdit = (index: number, row: EquipmentInfo[]) => {
  oldData.value=toIndependent(row)
  newData.value=toIndependent(oldData.value)
  console.log(newData);
  showFormWindow(false);
};
const handleDelete = (index:number, row:EquipmentInfo) => {
  equipmentStore.length = equipmentStore.length - 1;
  LogisticsApi.deleteEquipment(row.id).then(r=>{
    getEquipments().then(r=>{
      ElMessage.success("删除成功")
    })
  })
};
const toIndependent=(json:object)=>{
  return JSON.parse(JSON.stringify(json))
}
// 显示的表格
const filterTableData = computed(() => {
    return equipmentStore.filter(
      (data,index) => {
        // 编号从1开始
        index+=1
        let result=true
        // 搜索过滤
        result=!searchE.value ||
          data.name.toLowerCase().includes(searchE.value.toLowerCase());
        // 翻页实现
        result=result&&index<=(page.value)*limit.value&&index>(page.value-1)*limit.value
        return result
      }
    );
  }
)

// 导出的数据
const thisDataToExcel = () => {
  return equipmentStore.filter((data, index) => {
    // 编号从1开始
    index += 1;
    data.createdAt = formatDate(data.createdAt)
    data.id = index;
    return true;
  });
}
// 表格日期格式化
const formatTableDate=(row, column)=> {
  // 获取单元格数据
  let data = row[column.property]
  if(data == null) {
    return null
  }
  return formatDate(data)
}
// 日期格式化实现
const formatDate = (data) => {
  let dt = new Date(data)
  // dt=dt.getFullYear() + '-' + (dt.getMonth() + 1) + '-' + dt.getDate() + 'T' + dt.getHours() + ':' + dt.getMinutes() + ':' + dt.getSeconds()+'Z'
  return dt.toLocaleString().replaceAll('/','-')
}
onMounted(()=>{
  getEquipments()
})
</script>

<template>
  <div class="equipment1">
    <el-button type="success" class="addDataBtn" @click="showFormWindow(true)">添加数据</el-button>
    <el-button type="warning" class="addDataBtn" @click="exportExcel(thisDataToExcel(), ['id','name','location','status','createdAt'],['编号','名称','位置','状态','创建时间'],'设备表' + new Date().toLocaleString() + '.xlsx')"
    >导出数据
    </el-button>
    <el-table
      :data="filterTableData"
      style="width: 100%; margin-bottom: 20px; z-index: 0"
      row-key="id"
      border
      default-expand-all
    >
      <el-table-column label="编号" min-width="110">
        <template #default="scope">
          {{ (scope.$index+1)+(page-1)*limit }}
        </template>
      </el-table-column>
      <el-table-column prop="name" label="名称" sortable min-width="180"/>
      <el-table-column prop="location" label="位置" min-width="180" sortable/>
      <el-table-column prop="status" label="状态" min-width="180" sortable/>
      <el-table-column prop="createdAt" label="创建时间" :formatter="formatTableDate" min-width="240" sortable/>
      <el-table-column label="操作" width="140">
        <template #header>
          <el-input v-model="searchE" placeholder="搜索设备名称" />
        </template>
        <template #default="scope">
          <el-button type="warning"
                     size="small" @click="handleEdit(scope.$index, scope.row)"
          >编辑</el-button>
          <el-button
            size="small"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-model:limit="limit"
      v-model:page="page"
      v-model:total="equipmentStore.length"
    />
<!--    添加与修改公用弹窗-->
    <el-dialog v-model="showEditWindow" :title="isAddMode?'新增':'编辑'" width="500">
      <el-form label-width="85" :model="newData" :rules="dataRules">
        <el-form-item label="名称：" prop="name">
          <el-input v-model="newData.name" :placeholder="oldData.name"/>
        </el-form-item>
        <el-form-item label="位置：" prop="location">
          <el-input v-model="newData.location" :placeholder="oldData.location"/>
        </el-form-item>
        <el-form-item label="状态：" prop="status">
          <el-select v-model="newData.status" placeholder="avalible">
            <el-option v-for="i in statusList" :key="i" :label="i" :value="i" />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间：" prop="createdAt">
          <el-date-picker type="datetime" v-model="newData.createdAt" :placeholder="oldData.createdAt" style="width: 100%;"/>
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="confirmData()">确认</el-button>
          <el-button v-show="!isAddMode" type="warning" @click="resetData()">重置</el-button>
          <el-button type="danger" @click="clearData()">清空</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.equipment1{
  padding-top: 10px;
}
.addDataBtn{
  border-radius: 8px 8px 0px 0px ;
}
</style>
